package com.poetry.util;

import com.poetry.constant.FormatConstant;
import com.poetry.constant.RedisConstant;
import com.poetry.exception.UnauthorizedException;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.MailAuthenticationException;
import org.springframework.mail.MailSendException;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;
import org.thymeleaf.TemplateEngine;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.regex.Pattern;

@Component
@Slf4j
public class EmailUtil {
    @Resource
    private JavaMailSender mailSender;
    @Resource
    private TemplateEngine templateEngine;
    private final StringRedisTemplate redisTemplate;
    @Value("${app.verification.code-expire-minutes}")
    private Integer codeExpireMinutes;

    public EmailUtil(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }

    public Boolean checkEmail(String email) {
        return Pattern.compile(FormatConstant.EMAIL_PATTERN).matcher(email).matches();
    }

    public void sendVerificationCode(String to) {
        String code = redisTemplate.opsForValue().get(RedisConstant.LOGIN_CODE_KEY + to);
        try {
            SimpleMailMessage message = new SimpleMailMessage();
            message.setFrom("soul_999999@qq.com");
            message.setTo(to);
            message.setSubject("您的验证码");
            message.setText("您的验证码是：" + code + "，请在2分钟内使用");
            mailSender.send(message);
        } catch (MailAuthenticationException e) {
            log.error("邮件认证失败: {}", e.getMessage());
            throw new UnauthorizedException("邮箱认证失败，请检查配置");
        } catch (MailSendException e) {
            log.error("邮件发送失败: {}", e.getMessage());
            log.error("失败原因: {}", e.getFailedMessages());
            throw new UnauthorizedException("邮件发送失败");
        } catch (Exception e) {
            log.error("未知错误: {}", e.getMessage());
            throw new UnauthorizedException("邮件发送失败");
        }
    }

    /**
     * 生成验证码
     * @return
     */
    private String generateCode() {
        Random r = new Random();
        return String.format("%06d", r.nextInt(999999));
    }

    public void saveCode(String email) {
        //redisTemplate.delete(email);
        String key = RedisConstant.LOGIN_CODE_KEY + email;
        redisTemplate.opsForValue().set(key, generateCode(), codeExpireMinutes, TimeUnit.MINUTES);
    }

    public Boolean verifyCode(String email, String code) {
        String storeCode = redisTemplate.opsForValue().get(RedisConstant.LOGIN_CODE_KEY + email);
        return storeCode != null  && storeCode.equals(code);
    }
}
